package services;

import java.util.List;
import javax.persistence.Query;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import org.apache.commons.collections.CollectionUtils;
import org.apache.openjpa.persistence.PersistenceException;
import domains.Image;
import domains.User;

public class ImageService implements IImageService {
	EntityManagerFactory tmp;
	
	public ImageService(EntityManagerFactory emf) {
		tmp = emf;
	}

	@Override
	public Image findImageById (Integer id) throws PersistenceException {
			if (id == null) {
				throw new PersistenceException("Image id for getting cannot be null!", null, id, false);
			}
			// Creating entity manager to work with entity
			EntityManager entityManager = tmp.createEntityManager();
			// Begin a new local transaction so that we can persist a new entity
			entityManager.getTransaction().begin();
			Image image = null;
			try {
				// Finding User by its id
			    image = entityManager.find(Image.class, id);
				// Commit the transaction, which will cause the entity to
				// be stored in the database
				entityManager.getTransaction().commit();
			} 
			catch (Exception e) {
				// Catching exceptions and rollback of transaction
				entityManager.getTransaction().rollback();
				// throwing exception further
				throw new PersistenceException(null, null, e, false);
			} finally {
				// It is always good practice to close the EntityManager so that
				// resources are conserved.
				entityManager.close();
			}
			return image;
	}
	
	@Override
	public Image findImageByDescriptionOfUser(String description, Integer id_user) {
		Image image = null;
		EntityManager em = tmp.createEntityManager();
		em.getTransaction().begin();
	
		try {
			// Создаем объект запроса
			Query query = em.createQuery("SELECT x FROM Image x WHERE x.description = ?1 AND x.user = ?2");
			query.setParameter(1,description);
			User user = DAOFactory.getInstance().getUserService().findUserById(id_user);
			query.setParameter(2, user);
			List<Image> list = query.getResultList();
			 if (CollectionUtils.isNotEmpty(list)) 
				image = list.get(0);
			em.getTransaction().commit();
		} 
		catch (Exception e) {
			e.printStackTrace();

			// Откат транзакции в случае ошибки
			em.getTransaction().rollback();
		} 
		finally {

			// Завершение работы с менеджером сущностей
			em.close();
		}
		return image;
	}

	@Override
	public List<Image> getImagesOfUser(Integer id_user) {
		List<Image> list = null;
		EntityManager em = tmp.createEntityManager();
		em.getTransaction().begin();
	
		try {
			// Создаем объект запроса
			Query query = em.createQuery("SELECT x FROM Image x WHERE x.user = ?1");
			User user = DAOFactory.getInstance().getUserService().findUserById(id_user);
			query.setParameter(1, user);
			if (!query.getResultList().isEmpty())
			  list = query.getResultList();
			em.getTransaction().commit();
		} 
		catch (Exception e) {
			e.printStackTrace();

			// Откат транзакции в случае ошибки
			em.getTransaction().rollback();
		} 
		finally {

			// Завершение работы с менеджером сущностей
			em.close();
		}
		return list;
	}

	@Override
	public void deleteImageById(Integer id_image) {
	   if (id_image == null) return;
	   
	  // Creating entity manager to work with entity
	  EntityManager entityManager = tmp.createEntityManager();
	  //Begin a new local transaction so that we can persist a new entity
	  entityManager.getTransaction().begin();

	try {
	 // Finding image by its id
	 Image image_del = entityManager.find(Image.class, id_image);

	 // Removing image
	 entityManager.remove(image_del);
 
	 // Commit the transaction, which will cause the entity to
	 // be stored in the database
	 entityManager.getTransaction().commit();

	} 
	
	catch (Exception e) {
  // Catching exceptions and rollback of transaction
	entityManager.getTransaction().rollback();
	// throwing exception further
	throw new PersistenceException(null, null, e, false);
	} 
	
	finally {
	// It is always good practice to close the EntityManager so that
	// resources are conserved.
	entityManager.close();
    }
	return;
  }

	@Override
	public int addImageOfUser(Integer id_user, String description, String name, Integer height, Integer width) {
		User user = DAOFactory.getInstance().getUserService().findUserById(id_user);
		if (user==null) return 1; //пользователя с таким id с существует
		EntityManager em = tmp.createEntityManager();
		em.getTransaction().begin();
	 try {	
		Image image = new Image();
		image.setDescription(description);
		image.setName(name);
		image.setImageHeight(height);
		image.setImageWidth(width);
		image.setUser(user);
		
		em.persist(image);
	    em.getTransaction().commit();
	 } 	
	 catch (Exception e) {
		e.printStackTrace();
		em.getTransaction().rollback();
	 }	
	 finally {
	    em.close();
	 }	
	 return 0;
  }
	
	@Override
	public int updateImage(Integer id_image, String description) {
		Image image = DAOFactory.getInstance().getImageService().findImageById(id_image);
		if (image==null) return 1; //изображения с таким id нету в БД
		
		EntityManager em = tmp.createEntityManager();
		em.getTransaction().begin();
	 try {	
		Image image2 = em.find(Image.class, image.getId());
		image2.setDescription(description);
		image2.setName(image.getName());
		image2.setImageHeight(image.getImageHeight());
		image2.setImageWidth(image.getImageWidth());
		image2.setUser(image.getUser());
		 
	    em.getTransaction().commit();
	 } 	
	 catch (Exception e) {
		e.printStackTrace();
		em.getTransaction().rollback();
	 }	
	 finally {
	    em.close();
	 }	
	 return 0;
	}

}
